<?php


namespace app\api\service;

use app\api\model\Goods;
use app\api\model\Redis as redisService;
class Redis{


    protected $redis;

    public function __construct(){
        $this->redis = new \Redis();
        $this->redis->connect('127.0.0.1',6379);
    }

    //抢购
    public function buying($uid,$goodsid){

        if($this->redis->lLen('goods_list'.$goodsid) == 0){
            return ['code'=>-1,'msg'=>'对不起已售罄'];
        }
        if($this->redis->sIsMember('exist'.$goodsid,$uid)){
            return ['code'=>-1,'msg'=>'对不起,您已购买不能重复购买了'];
        }
        //先扣除缓存中的数据
        if(!$this->redis->lPop('goods_list'.$goodsid)){
            return ['code'=>-1,'msg'=>'对不起已售罄'];
        };


        //写入订单
        $redis = new redisService();
        $redis->memberid = $uid;
        $redis->goodsid = $goodsid;
        $redis->num = 1;
        $redis->createtime = time();
        $redis->save();

        //修改商品的数量
        $goods = new Goods();
        $goodsItem = $goods->where('id',$goodsid)->find();
        if(empty($goodsItem)){}{
            return json(['code'=>-1,'msg'=>'该商品不存在或已删除']);
        }

        $goodsItem->num = $goodsItem->num - 1;
        $goodsItem->save();
        //购买人的记录,防止多次抢购
        $this->redis->sAdd('exist'.$goodsid,$uid);

        if($redis->id){
            return ['code'=>1,'data'=>$redis->id];
        }

        return ['code'=>1,'msg'=>'抢购成功'];


    }

    //设置库存
    public function inventory($goodsid){
        //参与抢购的数量
        $num = $goodsid == 1 ? 10 : 5;
        //缓存中的数量
        $len = $this->redis->lLen('goods_list'.$goodsid);
        //缓存中剩余的数量
        $count = $num - $len;
        if($count == 0){//实际库存为0的时候表示该商品已经全部售罄,如果在售就要补充数量了
            for ($i=1;$i<=$count;$i++){
                $this->redis->lPush('goods_list'.$goodsid,1);
            }
            return ['code'=>1,'msg'=>'抢购活动增加成功'];

        }
        return ['code'=>1,'msg'=>'抢购的商品还存在'];
    }

    //获取数据
    public function getData($id){
        echo  $this->redis->lLen('goods_list'.$id);
        echo '<pre>';
        print_r($this->redis->lRange('goods_list'.$id,0,-1));
        echo '<pre>';
        print_r($this->redis->sMembers('exist'.$id));die;
    }

    //获取数据列表
    public function getKeys(){

        $this->redis->del('age');

        print_r($this->redis->keys('*'));die;
    }




}